package com.scalpel.common.util;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

/**
 * @author chace.cai   xu
 * @description
 * 解析xml
 * @date 2016/4/1
 */
public class XMLUtils {
    static Logger logger=Logger.getLogger(XMLUtils.class);

    /**直接根据nodes来获取消息*/
    public static String getSpecifyElementTextAllInOne(String res,String... nodes) throws Exception {
        Document document= formatStr2Doc(res);
        if (document==null){return null;}
        Element rootElt = document.getRootElement();
        return getSpecifyElementText(rootElt,nodes);
    }

    public static Document formatStr2Doc(String xml) throws Exception{
        if("apiFail".equalsIgnoreCase(xml)){return null;}
        if(org.apache.commons.lang.StringUtils.isBlank(xml) || !org.apache.commons.lang.StringUtils.containsIgnoreCase(xml, "<?xml")){
            logger.error("传入的xml内容不对!"+xml);
            return null;
        }
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
        } catch (DocumentException e) {
            logger.error("格式化xml文档失败！DocumentException");
            return null;
        } catch (UnsupportedEncodingException e) {
            logger.error("格式化xml：UnsupportedEncodingException");
            return null;
        }catch (Exception x){
            logger.error("格式化xml：报错");
            return null;
        }
        return document;
    }
    /**
     * 获取指定元素下面的某层指定元素内容
     */
    public static String getSpecifyElementText(Element root,String... firstElement) throws  Exception{
        String text=null;
        String[] nodes=firstElement;
        int length=nodes.length;
        for(int i=0;i<length;i++){
            String node=nodes[i];
            if(i==(length-1)){
                if(root==null){
                    return null;
                }
                Element last=root.element(node);
                if(last!=null){
                    text=last.getTextTrim();
                }
            }else{
                if(root==null){
                    return null;
                }
                root=root.element(node);

            }
        }
        return text;
    }
}
